package samsung.sds.system.security.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import samsung.sds.system.security.service.SecurityManagerService;
import samsung.sds.system.utils.Constants;
import samsung.sds.userManagement.model.UserEntity;

@SuppressWarnings("deprecation")
@Service("userSecurityService")
public class UserSecurityService implements UserDetailsService {
	
	public static Logger logger = Logger.getLogger(UserSecurityService.class);

	@Autowired 
	private SecurityManagerService securityManagerServiceImpl;
	
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		UserDetails user = null;
		UserEntity sysUser = securityManagerServiceImpl.getSystemUser(username);
		if(sysUser != null){
			boolean status = true;
			if(!sysUser.getUser_status().equals(Constants.USER_STATUS_NORMAL)){
				status = false;
			}
			user =  new User(sysUser.getUsername(),sysUser.getPassword(),status,true,true,true,getAuthorities(sysUser));
			securityManagerServiceImpl.updateLastLoginTime(username);
		}else{
			logger.error("用户名或密码错误!");
		}
		return user;
	}
	
	private List<GrantedAuthority> getAuthorities(UserEntity sysUser){
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
		
		List<String> roleList = securityManagerServiceImpl.getRoleNameList(sysUser.getUsername());
		if(roleList != null && roleList.size() >0 ){
			for(String role : roleList){
				authList.add(new GrantedAuthorityImpl(role));
			}
		}
		return authList;
	}
	
}
